package com.uw.tookit;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class InformationActivity extends Activity {

	private InformationPageData data;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// Required 
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.location);
	    
	    // Get the business ID for the location you want to query
	    Bundle extras = getIntent().getExtras();
	    int businessID = extras.getInt("businessID");
	    
	    // Resources for manipulating strings
	    Resources res = getResources();
	    
	    
	    // Get the data to be displayed on this page
	    this.data = InformationFactory.getLocationData(businessID);
	    
	    // Check to make sure server connection worked/businessID was valid
	    if ( data == null ){
	    	// Set up the AlertDialog for an error
	    	AlertDialog failedDialog = 
	    			new AlertDialog.Builder(InformationActivity.this).create();
	        failedDialog.setMessage(res.getString(R.string.noNetworkError));
	      	failedDialog.setButton("OK", new DialogInterface.OnClickListener() {
	      		public void onClick(DialogInterface dialog, int which) {
	      			// Can't get the info so close the activity
	      			finish();
	      		}
	      	});
      	  failedDialog.show();
	    }
	    else {
		    // Set name
		    String nameText = 
		    		String.format(res.getString(R.string.locationNameText), 
		    				data.getLocationName());
		    TextView toChange = (TextView)findViewById(R.id.locationNameText);
		    toChange.setText(nameText);
		    
		    // Set category
		    String categoryText = 
		    		String.format(res.getString(R.string.locationCategoryText), 
		    				data.getCategory());
		    toChange = (TextView)findViewById(R.id.locationCategoryText);
		    toChange.setText(categoryText);
		    
		    // Set Description
		    String descriptionText = 
		    		String.format(
		    				res.getString(R.string.locationDescriptionText), 
		    				data.getDescription());
		    toChange = (TextView)findViewById(R.id.locationDescriptionLabel);
		    toChange.setText(descriptionText);
		    
		    // display ratings
		    displayRatings(data.getGoodRatings(), data.getBadRatings());
		    
		    //set icon
		    ImageView icon = 
		    		(ImageView)findViewById(R.id.locationCategoryImage);
		    icon.setImageResource(data.locationImageID());
		    
		    // Add button listeners.
		    addListenerOnMapButton();
		    addListenerOnDirectionButton();
		    addListenerOnBadButton();
		    addListenerOnGoodButton();
		    
	    }    
	}
	/**
	 * Changes the rating text, useful because it needs to change when 
	 * you rate something as good or bad
	 */
	private void displayRatings(int good, int bad) {
		String ratingsText = "";
		
		// Setup the ratings text
		if(good != -1 && bad != -1) {
			// Ratings are enabled so set the ratings text for display
			Resources res = getResources();
			ratingsText = 
					String.format(res.getString(R.string.locationRatingsText), 
							good, bad);
		}
		else {
			// If ratings are not enabled for this location, disable them
			disableRatings();
		}
		// Set the ratings text
		TextView toChange = (TextView)findViewById(R.id.locationRatingsLabel);
		toChange.setText(ratingsText);
	}
	/**
	 * Disables the good and bad ratings buttons
	 */
	private void disableRatings() {
		Button good = (Button)findViewById(R.id.locationGoodButton);
		good.setEnabled(false);
		Button bad = (Button)findViewById(R.id.locationBadButton);
		bad.setEnabled(false);
	}
	
	/**
	 * Opens the map with a pin for this location
	 */
	public void addListenerOnMapButton() {
    	final Button button = (Button) findViewById(R.id.locationMapButton);
    	button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent resultsPage = 
						new Intent(InformationActivity.this, CampusMap.class);
	            resultsPage.putExtra("lat", data.getLatitude());
	            resultsPage.putExtra("lon", data.getLongitude());
	            resultsPage.putExtra("name", data.getLocationName());
	            resultsPage.putExtra("businessID", data.getBusinessID());
	            startActivityForResult(resultsPage, 0);		
			}
    	});
	}
	
	/**
	 * A listener for the good ratings button. Sends a request to the server
	 * in order to 
	 */
	public void addListenerOnGoodButton() {
    	final Button button = (Button) findViewById(R.id.locationGoodButton);
    	button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				sendRating(1);
				disableRatings();
				displayRatings(data.getGoodRatings() + 1, data.getBadRatings());
			}
    	});
	}
	/**
	 * Sends a bad rating to the server when the Bad rating button is clicked
	 */
	public void addListenerOnBadButton() {
    	final Button button = (Button) findViewById(R.id.locationBadButton);
    	button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				sendRating(0);
				disableRatings();
				displayRatings(data.getGoodRatings(), data.getBadRatings() + 1);
			}
    	});
	}
	/**
	 * Send a rating to the server
	 * @param rating specify a rating to send only 
	 */
	private void sendRating(int rating) {
		// check for invalid parameter
		if(rating != 0 || rating != 1) {
			// Sending this to the server wouldn't do anything anyway, 
			//so why not just do nothing
			return;
		}
		
		// Setup the parameters to be sent to the server
		Map<String, String> params = new HashMap<String, String>();
		params.put("bid", "" + data.getBusinessID());
		params.put("rating", "" + rating);
		
		// Send the rating to the server
		ServerCommunicator.executeHttpRequest("search.php", 
				params );
	}
	
	/**
	 * Direct to Map and mark the path from user's current location
	 *  to the destination.
	 */
	public void addListenerOnDirectionButton() {
    	final Button button = 
    			(Button) findViewById(R.id.locationDirectionsButton);
    	button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent resultsPage = 
						new Intent(InformationActivity.this, GetPath.class);
	            resultsPage.putExtra("lat", data.getLatitude());
	            resultsPage.putExtra("lon", data.getLongitude());
	            resultsPage.putExtra("name", data.getLocationName());
	            resultsPage.putExtra("businessID", data.getBusinessID());
	            startActivityForResult(resultsPage, 0);		
			}
    	});
	}
	
	

}
